package com.taptech.doufu.ui.view.search;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.taptech.doufu.R;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.ui.view.TagViewGroup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class FilterView extends LinearLayout {
    private Context mContext;
    private View layFilter,laySort,btnSort,btnFilter,layBg,btnReset,btnFinish,ivLeftArrow,ivRightArrow;
    private ListView mListView;
    private TextView tvSort;
    private String selectSort = "综合排序";
    private HashMap<String, String> selectFilter = new HashMap<>();
    private FilterSortAdapter adapter;
    private ViewGroup layFilterContent;
    private OnFilterListen onFilterListen;
    public FilterView(Context context) {
        super(context);
        this.mContext = context;
        init();
    }

    public FilterView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init();

    }

    public FilterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init();
    }

    private void setSortList() {
        List<String> sortList = new ArrayList<>();
        sortList.add("综合排序");
        sortList.add("最近更新");
        sortList.add("收藏量");
        sortList.add("综合分");
        adapter.setData(sortList,selectSort);
    }

    private void setFilterData() {
        LinkedHashMap<String, List<String>> hashMap = new LinkedHashMap<>();
        List<String> list1 = new ArrayList<>();
        list1.add("连载");
        list1.add("完结");
        hashMap.put("进度", list1);
        List<String> list2 = new ArrayList<>();
        list2.add("免费");
        list2.add("付费");
        list2.add("会员免费");
        hashMap.put("价格", list2);

        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            final Map.Entry<String,List<String>> entry = (Map.Entry<String, List<String>>) iterator.next();
            View view = LayoutInflater.from(mContext).inflate(R.layout.view_filter, null);
            final TagViewGroup filterGroup = view.findViewById(R.id.filterGroup);
            TextView tvFilterTitle = view.findViewById(R.id.tvFilterTitle);
            tvFilterTitle.setText(entry.getKey());
            for (int i = 0; i < entry.getValue().size(); i++) {
                View itemView = LayoutInflater.from(mContext).inflate(R.layout.view_filter_item, null);
                final TextView textView = itemView.findViewById(R.id.tvContent);
                textView.setHeight(ScreenUtil.dip2px(mContext,30));
                textView.setBackgroundResource(R.drawable.bg_tag_2radius);
                textView.setTextColor(ContextCompat.getColor(mContext,R.color.text_color_1));
                textView.setText(entry.getValue().get(i));
                final int finalI = i;
                textView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView curTextView = (TextView) filterGroup.getChildAt(finalI);
                        if (selectFilter.containsValue(curTextView.getText().toString())) {
                            selectFilter.remove(entry.getKey());
                            curTextView.setTextColor(ContextCompat.getColor(mContext,R.color.text_color_1));
                            curTextView.setBackgroundResource(R.drawable.bg_tag_2radius);
                        }else{
                            for (int j = 0; j < entry.getValue().size(); j++) {
                                TextView tv = (TextView) filterGroup.getChildAt(j);
                                if (finalI == j) {
                                    selectFilter.put(entry.getKey(), entry.getValue().get(j));
                                    tv.setTextColor(ContextCompat.getColor(mContext,R.color.text_color_57));
                                    tv.setBackgroundResource(R.drawable.bg_tag_2radius_select);
                                }else{
                                    tv.setTextColor(ContextCompat.getColor(mContext,R.color.text_color_1));
                                    tv.setBackgroundResource(R.drawable.bg_tag_2radius);
                                }
                            }
                        }

                    }
                });
                filterGroup.addView(itemView);
            }
            layFilterContent.addView(view);
        }
    }

    private void init() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_search_filter,null);
        layFilterContent = view.findViewById(R.id.layFilterContent);
        ivLeftArrow = view.findViewById(R.id.ivLeftArrow);
        ivRightArrow = view.findViewById(R.id.ivRightArrow);
        btnFinish = view.findViewById(R.id.btnFinish);
        tvSort = view.findViewById(R.id.tvSort);
        btnReset = view.findViewById(R.id.btnReset);
        mListView = view.findViewById(R.id.mListView);
        adapter = new FilterSortAdapter(mContext);
        mListView.setDividerHeight(0);
        mListView.setAdapter(adapter);
        setSortList();
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectSort = adapter.getItem(position);
                tvSort.setText(selectSort);
                hideContentLayout();
                if (onFilterListen != null) {
                    onFilterListen.onSort(selectSort);
                }
            }
        });
        layFilter = view.findViewById(R.id.layFilter);
        layBg = view.findViewById(R.id.layBg);
        laySort = view.findViewById(R.id.laySort);
        btnSort = view.findViewById(R.id.btnSort);
        btnFilter = view.findViewById(R.id.btnFilter);
        btnSort.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (laySort.getVisibility() == VISIBLE) {
                    //隐藏
                    translationYAnimation(laySort,false);
                    rotationAnimation(ivLeftArrow,false);
                    layBg.setVisibility(GONE);
                }else{
                    setSortList();
                    translationYAnimation(layFilter,false);
                    rotationAnimation(ivRightArrow,false);
                    translationYAnimation(laySort, true);
                    rotationAnimation(ivLeftArrow,true);
                    layBg.setVisibility(VISIBLE);
                }
            }
        });
        btnFilter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (layFilter.getVisibility() == VISIBLE) {
                    translationYAnimation(layFilter,false);
                    rotationAnimation(ivRightArrow,false);
                    layBg.setVisibility(GONE);
                }else{
                    translationYAnimation(laySort,false);
                    rotationAnimation(ivLeftArrow,false);
                    translationYAnimation(layFilter,true);
                    rotationAnimation(ivRightArrow,true);
                    layBg.setVisibility(VISIBLE);
                }
            }
        });
        layBg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                hideContentLayout();
            }
        });
        btnReset.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                resetFilter();
            }
        });
        btnFinish.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onFilterListen != null) {
                    onFilterListen.onFilter(selectFilter);
                }
                hideContentLayout();
            }
        });
        setFilterData();
        hideContentLayout();
        addView(view);
    }

    /**
     * 暴露的接口
     * （1）初始化数据
     * （2）受外部影响的内容：隐藏筛选框、隐藏并重置筛选框
     * （3）提供外部需要的结果数据，被动
     * （4）通知外部结果数据，主动
     *
     * @param view
     * @param isVisible
     */


    private void translationYAnimation(final View view, final boolean isVisible) {
        float start,end;
        if (isVisible) {
            view.setVisibility(VISIBLE);
            //显示
            start = -view.getHeight();
            end = 0;
        }else{
            //隐藏
            start = 0;
            end = -view.getHeight();
        }
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "translationY",  start,end);
        objectAnimator.setDuration(300);
        objectAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (isVisible) {
                    view.setVisibility(VISIBLE);
                }else{
                    view.setVisibility(GONE);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        objectAnimator.start();
    }

    private void rotationAnimation(View view, boolean isVisible/*显示布局*/) {
        float start,end;

        if (isVisible) {
            //显示
            start = 0;
            end = 180;
        }else{
            //隐藏
            start = 180;
            end = 0;
        }
        if (view.getRotation() == end) {
            return;
        }
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "rotation",  start,end);
        objectAnimator.setDuration(300);
        objectAnimator.start();
    }

    private void hideContentLayout() {
        translationYAnimation(laySort,false);
        translationYAnimation(layFilter,false);
        rotationAnimation(ivLeftArrow,false);
        rotationAnimation(ivRightArrow,false);
        layBg.setVisibility(GONE);
    }

    /**
     * 重置排序
     */
    private void resetSort() {
        selectSort = "综合排序";
        tvSort.setText(selectSort);
        setSortList();
    }

    /**
     * 重置智能筛选
     */
    private void resetFilter() {
        layFilterContent.removeAllViews();
        selectFilter.clear();
        setFilterData();
    }


    public void hideLayout(boolean isReset) {
        hideContentLayout();
        if (isReset) {
            resetSort();
            resetFilter();
        }
    }

    public void setOnFilterListen(OnFilterListen onFilterListen) {
        this.onFilterListen = onFilterListen;
    }

    public String getSelectSort() {
        return selectSort;
    }

    public HashMap<String, String> getSelectFilter() {
        return selectFilter;
    }
}
